package cn.com.cifi.mars.web.action.report;

import cn.com.cifi.mars.bean.vo.report.CityReturnCoefficientReportVo;
import cn.com.cifi.mars.bean.vo.report.ProjectReturnCoefficientReportVo;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.BigStandardFormatsEnum;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.constant.StandardFormatsMapEnum;
import cn.com.cifi.mars.entity.DmCityReturnCoefficient;
import cn.com.cifi.mars.mapper.mars.DmProjectReturnCoefficientMapper;
import cn.com.cifi.mars.service.DmCityReturnCoefficientService;
import cn.com.cifi.mars.service.DmProjectReturnCoefficientReportService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.util.CityReturnCoefficientTemplate;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.ProjectReturnCoefficientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: JingYuanXiang
 * @date: 2020/12/15 16:58
 */
@Slf4j
@RestController
public class ReturnCoefficientReportController extends BaseAction implements IReturnCoefficientReportController {

    @Autowired
    private DmProjectReturnCoefficientReportService dmProjectReturnCoefficientReportService;
    @Autowired
    private DmCityReturnCoefficientService dmCityReturnCoefficientService;
    @Autowired
    private DmProjectReturnCoefficientMapper dmProjectReturnCoefficientMapper;
    @Autowired
    private IdmUserService idmUserService;

    @Override
    public R refreshdmProjectReturnCoefficient(String apiVersion, String projectId, String yearMonth) {
        dmProjectReturnCoefficientReportService.refreshdmProjectReturnCoefficient(projectId, yearMonth);
        return ok();
    }

    @Override
    public R<List<ProjectReturnCoefficientReportVo>> dmProjectReturnCoefficient(String apiVersion, String yearMonth, String versionType, String vsVersionType) {
        //查询用户权限项目id列表
        List<String> projectIdList = idmUserService.queryUserProjectPermissions(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }

        List<ProjectReturnCoefficientReportVo> voList = dmProjectReturnCoefficientReportService.dmProjectReturnCoefficient(projectIdList,yearMonth, versionType, vsVersionType);
        return ok(voList);
    }

    @Override
    public void exportProjectReturnCoefficient(String apiVersion, HttpServletResponse response, String yearMonth) {
        //查询用户权限项目id列表
        List<String> projectIdList = idmUserService.queryUserProjectPermissions(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }

        List<ProjectReturnCoefficientReportVo> vo1List = dmProjectReturnCoefficientReportService.dmProjectReturnCoefficient(projectIdList,yearMonth, "practical", "investOfficial");
        List<ProjectReturnCoefficientReportVo> vo2List = dmProjectReturnCoefficientReportService.dmProjectReturnCoefficient(projectIdList,yearMonth, "adjustment", "practical");
        List<ProjectReturnCoefficientReportVo> vo3List = dmProjectReturnCoefficientReportService.dmProjectReturnCoefficient(projectIdList,yearMonth, "adjustment", "investOfficial");

        String name = "项目回款系数分析表-截止" + yearMonth.replace("-","")+"-"+ LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMddHH");

        ProjectReturnCoefficientTemplate projectReturnCoefficientTemplate = new ProjectReturnCoefficientTemplate(name);
        projectReturnCoefficientTemplate.appendRows(vo1List,0);
        projectReturnCoefficientTemplate.appendRows(vo2List, 1);
        projectReturnCoefficientTemplate.appendRows(vo3List, 2);
        try (OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
            projectReturnCoefficientTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("###### errorMsg: ", e);
        }
    }


    //手动刷新城市回款系数分析表
    @Override
    public R refreshDmCityReturnCoefficient(String apiVersion, String cityId, String yearMonth) {
        dmCityReturnCoefficientService.refreshDmCityReturnCoefficient(yearMonth);
        return ok();

    }

    @Override
    public R<List<CityReturnCoefficientReportVo>> dmCityReturnCoefficient(String apiVersion, String yearMonth) {
        List<CityReturnCoefficientReportVo> voList = dmCityReturnCoefficientService.dmCityReturnCoefficient(yearMonth);
        return ok(voList);
    }

    @Override
    public void exportCityReturn(String apiVersion, HttpServletResponse response, String yearMonth) {
        //归属时间
        LocalDateTime time = LocalDateTimeUtils.toLocalDateTime(yearMonth);

        //业态编码列表
        List<String> codeList = StandardFormatsMapEnum.getSortStandardFormatsCodeList();
        //数据列表
        List<DmCityReturnCoefficient> list = dmProjectReturnCoefficientMapper.selectDmCityReturnCoefficient(time);
        if(CollectionUtils.isNotEmpty(list)){
            list = list.stream()
                    .sorted(Comparator.comparing(DmCityReturnCoefficient::getCityName)
                            .thenComparing(s -> codeList.indexOf(s.getProProductCode())))
                    .collect(Collectors.toList());
        }
        String name = "城市回款系数分析表-截止"+yearMonth.replace("-","")+"-"+ LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMddHH");

        CityReturnCoefficientTemplate cityReturnCoefficientTemplate = new CityReturnCoefficientTemplate(name);
        cityReturnCoefficientTemplate.appendRows(list);
        try (OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
            cityReturnCoefficientTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("###### errorMsg: ", e);
        }

    }
}
